package com.fxn.adapters;

import com.futuremind.recyclerviewfastscroll.SectionTitleProvider;
import com.fxn.interfaces.OnVerticalListSelectionListener;
import com.fxn.modals.Img;
import com.fxn.pix.ResourceTable;
import com.fxn.utils.FileUtils;
import com.fxn.utils.LogUtil;
import com.fxn.utils.PixelUtil;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * description : MainAbility
 *
 * @since 2021-04-15
 */
public class MainImageAdapter extends BaseItemProvider implements SectionTitleProvider {
    /**
     * HEADER
     */
    public static final int HEADER = 1;

    /**
     * ITEM
     */
    public static final int ITEM = 2;
    private static final int MARGIN = (int) PixelUtil.vp2px(3);

    private int spanCount = 0;
    private List<List<Img>> mList;
    private OnVerticalListSelectionListener onSelectionListener;
    private final StackLayout.LayoutConfig mLayoutConfig;
    private final Context mContext;
    private final int headHeight;

    /**
     * 初始化 VerticalProvider
     *
     * @param context   context
     * @param spanCount VerticalProvider 的列数
     */
    public MainImageAdapter(Context context, int spanCount) {
        this.mContext = context;
        this.mList = new ArrayList<>();
        this.spanCount = spanCount;
        int size = (PixelUtil.screenWidth() - ((this.spanCount - 1) * MARGIN)) / this.spanCount;
        mLayoutConfig = new StackLayout.LayoutConfig(size, size);
        headHeight = (int) PixelUtil.vp2px(35);
    }

    /**
     * 添加 onSelectionListener监听
     *
     * @param onSelectionListener 监听回调
     */
    public void addOnSelectionListener(OnVerticalListSelectionListener onSelectionListener) {
        this.onSelectionListener = onSelectionListener;
    }

    /**
     * 获取provider的高
     *
     * @return provider的高
     */
    public int getProviderHeight() {
        int providerHeight = 0;
        LogUtil.loge("headHeight = " + headHeight + "; itemHeight = " + (mLayoutConfig.height + MARGIN));
        for (int i = 0; i < mList.size(); i++) {
            if (getItemComponentType(i) == HEADER) {
                providerHeight += headHeight;
            } else {
                providerHeight = providerHeight + mLayoutConfig.height + MARGIN;
            }
        }
        return providerHeight;
    }

    /**
     * 设置provider的数据源 list
     *
     * @param list provider的数据源
     * @throws RuntimeException RuntimeException
     */
    public void setList(ArrayList<Img> list) throws RuntimeException {
        if (spanCount == 0) {
            throw new SecurityException("请先设置SPAN_COUNT的值");
        }
        List<List<Img>> tempList = new ArrayList<>();
        List<Img> itemList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Img img = list.get(i);
            if ("".equals(img.getContentUrl())) {
                // 头布局
                if (tempList.size() > 0 && !tempList.contains(itemList)) {
                    tempList.add(itemList);
                }
                itemList = new ArrayList<>();
                itemList.add(img);
                tempList.add(itemList);
                itemList = new ArrayList<>();
                continue;
            }
            if (itemList.size() == spanCount) {
                itemList = new ArrayList<>();
            }
            itemList.add(img);
            if (itemList.size() == spanCount) {
                tempList.add(itemList);
            }
            if (i == list.size() - 1) {
                tempList.add(itemList);
            }
        }
        this.mList = tempList;
        notifyDataChanged();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int positon) {
        return mList.get(positon);
    }

    @Override
    public long getItemId(int positon) {
        return positon;
    }

    @Override
    public int getItemComponentType(int position) {
        if (mList.size() <= position) {
            return 0;
        }
        List<Img> imgs = mList.get(position);
        return ("".equals(imgs.get(0).getContentUrl())) ? HEADER : ITEM;
    }

    /**
     * 设置item的选中状态
     *
     * @param selection 是否选中
     * @param firstPos  item所在的行数
     * @param pos       item所在的列数
     */
    public void select(boolean selection, int firstPos, int pos) {
        mList.get(firstPos).get(pos).setSelected(selection);
        notifyDataSetItemChanged(firstPos);
    }

    /**
     * 根据传入的Img对象设置该对象所在item是否选中
     *
     * @param selection 是否选中
     * @param img       根据此img对象判断是否选中
     */
    public void select(boolean selection, Img img) {
        for (int i = 0; i < mList.size(); i++) {
            for (int j = 0; j < mList.get(i).size(); j++) {
                if (mList.get(i).get(j).getContentUrl().equals(img.getContentUrl())) {
                    select(selection, i, j);
                }
            }
        }
    }

    @Override
    public Component getComponent(final int position, Component component, ComponentContainer componentContainer) {
        List<Img> imgs = mList.get(position);
        Component tempComponent;
        if (getItemComponentType(position) == HEADER) {
            // 头布局
            tempComponent = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_header_row, null, false);
            if (tempComponent.findComponentById(ResourceTable.Id_header) instanceof Text) {
                Text mText = (Text) tempComponent.findComponentById(ResourceTable.Id_header);
                mText.setText(imgs.get(0).getHeaderDate());
            }
            return tempComponent;
        } else {
            // 子布局
            Component parse1 = LayoutScatter.getInstance(mContext)
                    .parse(ResourceTable.Layout_vertical_list_item, null, false);
            DirectionalLayout rootView = null;
            if (parse1 instanceof DirectionalLayout) {
                rootView = (DirectionalLayout) parse1;
            }
            ComponentContainer.LayoutConfig layoutConfig = rootView.getLayoutConfig();
            layoutConfig.height = mLayoutConfig.height;
            rootView.setLayoutConfig(layoutConfig);
            for (int i = 0; i < imgs.size(); i++) {
                Component tempParse = LayoutScatter.getInstance(mContext)
                        .parse(ResourceTable.Layout_main_image, null, false);
                if (tempParse instanceof StackLayout) {
                    StackLayout parse = (StackLayout) tempParse;
                    Image check = null;
                    Image preview = null;
                    Image videoIcon = null;
                    if (parse.findComponentById(ResourceTable.Id_selection) instanceof Image) {
                        check = (Image) parse.findComponentById(ResourceTable.Id_selection);
                    }
                    if (parse.findComponentById(ResourceTable.Id_preview) instanceof Image) {
                        preview = (Image) parse.findComponentById(ResourceTable.Id_preview);
                    }
                    if (parse.findComponentById(ResourceTable.Id_isVideo) instanceof Image) {
                        videoIcon = (Image) parse.findComponentById(ResourceTable.Id_isVideo);
                    }
                    if (i == imgs.size() - 1) {
                        mLayoutConfig.setMarginBottom(MARGIN);
                    } else {
                        mLayoutConfig.setMargins(0, MARGIN, MARGIN, MARGIN);
                    }
                    parse.setLayoutConfig(mLayoutConfig);
                    Img img = imgs.get(i);
                    if (img.getMediaType().contains("image")) {
                        // 图片
                        videoIcon.setVisibility(Component.HIDE);
                    } else {
                        videoIcon.setVisibility(Component.VISIBLE);
                    }
                    preview.setPixelMap(img.getPixelMap());
                    check.setVisibility(img.getSelected() ? Component.VISIBLE : Component.HIDE);
                    int finalI = i;
                    preview.setClickedListener(component1 -> {
                        if (onSelectionListener != null) {
                            onSelectionListener.onClick(img, component1, position, finalI);
                        }
                    });
                    preview.setLongClickedListener(component1 -> {
                        if (onSelectionListener != null) {
                            onSelectionListener.onLongClick(img, component1, position, finalI);
                        }
                    });
                    rootView.addComponent(parse);
                }
            }
            return rootView;
        }
    }

    @Override
    public String getSectionTitle(int position) {
        if (mList.get(position).size() > 0) {
            return mList.get(position).get(0).getHeaderDate();
        }
        return "";
    }
}
